#!/bin/sh

if [ "$1" = "--help" ]; then
    cat <<EOF
Usage: tp-compact-keyboard [OPTION...]

--help
    Print this help output.

--fn-lock-disable
    Disable "fn key lock". The the function keys will send media function
    keycodes (such as mute audio).

--fn-lock-enable
    Enable "fn key lock". The function keys will send the F keycodes (IE F1,
    F2, etc).
    
--native-fn-enable
    By default, F7/F9/F11 generate a string of keypresses that might be
    useful under windows. This stops this, and instead only generates
    custom events.
    
--native-mouse-enable
    The middle button generates 2 events by default, but Linux only
    understands one of them. This disables the event that Linux does
    understand, leaving you with no middle button.
    
--native-mouse-disable
    Restore middle button to a working state.

--sensitivity xx
    Set sensitivity of trackpoint. xx is hex value 01--09 (although values
    up to FF work).

EOF
    exit 0
fi

# Find the bluetooth keyboard
HID_NAME="ThinkPad Compact Bluetooth Keyboard with TrackPoint"
HIDRAWS=$(grep -l "HID_NAME=$HID_NAME" /sys/class/hidraw/hidraw*/device/uevent | grep -oE 'hidraw[0-9]+')
if [ -z "$HIDRAWS" ]; then
    echo "No keyboard found!"
    exit 1
fi

# Do command for all keyboards attached
for HIDRAW in $HIDRAWS; do
    if [ ! -w "/dev/$HIDRAW" ]; then
        echo "Permission denied: cannot write to /dev/$HIDRAW (are you root?)"
        exit 1
    fi
    if [ "$1" = "--fn-lock-disable" ]; then
        echo Disabling Fn lock for /dev/$HIDRAW...
        /bin/echo -ne "\x18\x05\x00" | dd of=/dev/$HIDRAW 2>/dev/null
    elif [ "$1" = "--fn-lock-enable" ]; then
        echo Enabling Fn lock for /dev/$HIDRAW...
        /bin/echo -ne "\x18\x05\x01" | dd of=/dev/$HIDRAW 2>/dev/null
    elif [ "$1" = "--native-fn-enable" ]; then
        echo Enabling native mode for F7/F9/F11 for /dev/$HIDRAW...
        /bin/echo -ne "\x18\x01\x03" | dd of=/dev/$HIDRAW 2>/dev/null
    elif [ "$1" = "--native-mouse-disable" ]; then
        echo Disabling native mode for middle button for /dev/$HIDRAW...
        /bin/echo -ne "\x18\x09\x00" | dd of=/dev/$HIDRAW 2>/dev/null
    elif [ "$1" = "--native-mouse-enable" ]; then
        echo Enabling native mode for middle button for /dev/$HIDRAW...
        /bin/echo -ne "\x18\x09\x01" | dd of=/dev/$HIDRAW 2>/dev/null
    elif [ "$1" = "--sensitivity" ]; then
        echo Setting sensitivity for /dev/$HIDRAW to $2...
        /bin/echo -ne "\x18\x02\x$2" | dd of=/dev/$HIDRAW 2>/dev/null
    else
        echo "No actions specified. Run --help to see possible actions."
    fi
done

# All HID DATA packets sent to keyboard on startup
# 18 01 03 - Make F7/F9/F11 return custom single events, as opposed to strings of keys
# 18 05 01 - Enable fn-lock
# 18 02 05 - Sensitivity, 01--09 in windows, 00--FF works
# 18 09 01 - Disable middle mouse button's standard response (leave custom one working)
